package com.kehutong.department.app;

import com.kehutong.common.util.Token;
import com.kehutong.department.entity.Department;
import com.kehutong.department.service.DepartmentService;
import org.coraframework.authz.HasPermission;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.Objects;

import java.util.*;

@MvcAction
@ReqMapping("/kht-bin/basic/department")
public class DepartmentAction {
	
	@Inject
	private JdbcSession jdbcSession;
	@Inject
	private DepartmentService departmentService;


	/**
	 * 触发角色权限必须增加HasPermission权限拦截不然不会自动拼接拦截部门信息的sql
	 * @param jsonObject
	 * @return
	 * @throws Exception
	 */
	@HasPermission("department:list:view")
	@ReqMapping("/list")
	public Object list(JSONObject jsonObject){
		List<Department> list = jdbcSession.findArray(Department.class)
				.eq("deleted", false)
				.like(jsonObject, "name").exe();

		List<JSONObject> result = new ArrayList<>();
        list.forEach(item -> {
            result.add(departmentService.department2JSONObject(item));
        });

        return result;
	}

	@ReqMapping("/get")
	public Object get(Department department){

		List<String> departmentName = new ArrayList<>();
		department.getParent_ids().forEach(id->{
			Department entity = Pool.get(Department.class, id);
			departmentName.add(entity.getName());
		});
		department.setParentNames(departmentName);

		return department;
	}

	/**
	 * 触发角色权限必须增加HasPermission权限拦截不然不会自动拼接拦截部门信息的sql
	 * @param token
	 * @param jsonObject
	 * @return
	 * @throws Exception
	 */
	@HasPermission("department:list:view")
	@ReqMapping("/getDepartment")
	public Object getDepartmentEmployee (Token token, JSONObject jsonObject) throws Exception {
		String parent_id = jsonObject.getString("parent_id");
		if(Objects.nonEmpty(parent_id)){
			return departmentService.doGetDepartmentEmployee(jsonObject);
		}else{
			return departmentService.doGetDepartmentEmployeeCreateRoot(token);
		}
	}

}
